﻿using DotNetty.Buffers;
using DotNetty.Transport.Channels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EchoServer
{
    public class EchoServerHandler : ChannelHandlerAdapter
    {
        /// <summary>
        /// 处理传入的消息
        /// </summary>
        /// <param name="context"></param>
        /// <param name="message"></param>
        public async override void ChannelRead(IChannelHandlerContext context, object message)
        {
            IByteBuffer msg = message as IByteBuffer;
            Console.WriteLine($"收到消息：{msg.ToString(Encoding.UTF8)}");
            await context.WriteAsync(msg);
        }

        /// <summary>
        /// 批量读取中的最后一条消息已经读取完成
        /// </summary>
        /// <param name="context"></param>
        public override void ChannelReadComplete(IChannelHandlerContext context)
        {
            context.Flush();
        }

        /// <summary>
        /// 发生异常
        /// </summary>
        /// <param name="context"></param>
        /// <param name="exception"></param>
        public async override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
        {
            Console.WriteLine(exception);
            await context.CloseAsync();
        }
    }
}
